<template>
  <a-modal width="55%" title="编辑" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk"
    @cancel="handleCancel">
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <a-row>
        <a-col :span="24">
          <a-button class="editable-add-btn" @click="handleAdd" type="primary"
            :style="{ 'margin-bottom': '10px' }">新增子工程量</a-button>
          <a-table :custom-row="customRow" bordered :data-source="dataSource" :columns="columns" :pagination="false">
            <template slot="groupChildGridId" slot-scope="text, record">
              <div>
                <a-input v-model="record.gridName" v-if="packageGridIdList.length == 0"></a-input>
                <a-select v-else placeholder="请选择" show-search optionFilterProp="children"
                  v-model="record.groupChildGridId" @change="changeGroupChildGridId(record.groupChildGridId, record)">
                  <a-select-option v-for="mode in packageGridIdList" :key="mode.id" :value="mode.id">{{ mode.gridName
                    }}</a-select-option>
                </a-select>
              </div>
            </template>
            <template slot="orderd" slot-scope="text, record">
              <div>
                <template>
                  <!-- {{ text }} -->
                  <!-- <a-input v-model="record.orderd" type="number" :min="1"></a-input> -->
                  <a-input v-model="record.orderd" :min="1" readonly />
                </template>
              </div>
            </template>
            <template slot="operation" slot-scope="text, record">
              <!-- <span style="margin-right: 10px">
                <a :disabled="editingKey !== ''" @click="() => editChildren(record)">编辑</a>
              </span>-->
              <a-popconfirm style="margin-right: 5px" v-if="dataSource.length" overlayClassName="poperLayTable"
                title="确定删除该数据?" @confirm="() => onDelete(record)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>

              <div class="editable-row-operations"></div>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-form-model>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import Vue from 'vue'
export default {
  data() {
    return {
      visible: false,
      falseFlag: false,
      length: 2,
      targetObj: {},
      sourceObj: {},
      model: {
        dataSource: [
          {
            key: '0',
            groupChildGridId: '',
            Values: [],
            length: 1,
            falseFlag: false,
            packageInfoId: this.packageInfoId,
            orderd: '1',
            editable1: true,
          },
        ],
        Values: [],
      },
      packageInfoId: '',
      groupGridId: '',
      editingKey: '',
      cacheData: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: '/grid/nmcPackageGridGroup/addBatch',
        delete: '/grid/nmcPackageGridGroup/delete',
        edit: '/grid/nmcPackageGridGroup/edit',
        addP: '/grid/nmcRelationPackageGrid/add',
        deleteP: '/grid/nmcRelationPackageGrid/delete',
        query: '/grid/nmcPackageGridGroup/queryChildGridByGroupGridId',
        editP: '/grid/nmcRelationPackageGrid/edit',
        PackageGridlist: '/grid/nmcPackageGrid/list',
        PackageInfoList: '/grid/nmcPackageInfo/list',
        nmcPackageGridValueList: '/grid/nmcPackageGridValue/list',
      },
      dataSource: [
        {
          key: '0',
          groupChildGridId: '',
          groupGridId: this.groupGridId,
          orderd: '1',
          falseFlag: false,
          length: 1,
          editable1: true,
        },
      ],
      count: 0,
      packageGridIdList: [],
      ipagination: [
        {
          isorter: {
            order: 'asc',
            column: 'orderd',
          },
        },
      ],

      columns: [
        {
          title: '组包排序',
          dataIndex: 'orderd',
          width: 90,
          // scopedSlots: { customRender: 'orderd' },
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '工程量',
          width: 180,
          dataIndex: 'groupChildGridId',
          scopedSlots: { customRender: 'groupChildGridId' },
        },
        {
          title: '字节长度',
          // width: 180,
          dataIndex: 'gridStaticLength',
          scopedSlots: { customRender: 'gridStaticLength' },
        },
        {
          title: '分辨率',
          dataIndex: 'resolvingPower',
          scopedSlots: { customRender: 'resolvingPower' },
        },
        // {
        //   title: '输入方式',
        //   dataIndex: 'GridInputMethod',
        //   width: '15%',
        //   scopedSlots: { customRender: 'GridInputMethod' },
        // },
        // {
        //   title: '是否特征值',
        //   dataIndex: 'isEigen',
        //   width: 110,
        //   scopedSlots: { customRender: 'isEigen' },
        // },
        // {
        //   title: '特征值',
        //   dataIndex: 'eigenValue',
        //   minWidth: 160,
        //   scopedSlots: { customRender: 'eigenValue' },
        // },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 120,
          scopedSlots: { customRender: 'operation' },
        },
      ],
      PackageInfoList: [],
      eigenValueList: [],
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.cacheData = [...this.dataSource]
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))

    // document.addEventListener('keyup', this.tabForward) //光标自动切换
  },
  methods: {
    changeGroupChildGridId(val, record) {
      console.log(val, record);
      let select = this.packageGridIdList.find(i => i.id == val)
      let data = this.dataSource.find(i => i.groupChildGridId == val).orderd
      console.log(this.dataSource[data - 1], '============');
      // this.dataSource[data - 1].gridStaticLength = select.gridStaticLength ? select.gridStaticLength : null
      // this.dataSource[data - 1].resolvingPower = select.resolvingPower ? select.resolvingPower : null
      Vue.set(this.dataSource[data - 1], 'gridStaticLength', select.gridStaticLength)
      Vue.set(this.dataSource[data - 1], 'resolvingPower', select.resolvingPower)

    },
    customRow(record, index, event) {
      console.log(record, 're', index, event)
      return {
        props: {
          // draggable: 'true'
        },
        on: {
          // 鼠标移入
          mouseenter: (event) => {
            // 兼容IE
            var ev = event || window.event
            ev.target.draggable = true //允许拖拽
          },
          //开始拖拽
          dragstart: (event) => {
            // 兼容IE
            var ev = event || window.event
            // 阻止冒泡
            ev.stopPropagation()
            // 得到源目标数据
            this.sourceObj = record
          },
          // 拖动元素经过的元素
          dragover: (event) => {
            // 兼容 IE
            var ev = event || window.event
            // 阻止默认行为
            ev.preventDefault()
          },
          // 鼠标松开
          drop: (event) => {
            // 兼容IE
            var ev = event || window.event
            // 阻止冒泡
            ev.stopPropagation()
            // 得到目标数据
            this.targetObj = record
            let cacheData = [...this.dataSource]
            let sourceIndex = 0
            let targetIndex = 0
            let that = this
            cacheData.forEach((el, index) => {
              if (el.id == that.sourceObj.id) {
                sourceIndex = index
              }
              if (el.id == that.targetObj.id) {
                targetIndex = index
              }
            });
            //拖拽互换
            // var temp1 = cacheData[sourceIndex];
            // cacheData[sourceIndex] = cacheData[targetIndex];
            // cacheData[targetIndex] = temp1;
            //拖拽插入
            let obj = cacheData[sourceIndex]
            cacheData.splice(sourceIndex, 1);
            cacheData.splice(targetIndex, 0, obj);
            this.dataSource = [...cacheData]
          }
        },
        attrs: {
          draggable: record.draggable,
        },
      };
    },
    showModal() {
      this.visible = true
    },
    handleOk(e) {
      console.log('提交')
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          // that.confirmLoading = true
          let httpurl = ''
          let method = ''
          let flag = false
          this.dataSource.forEach((i, index) => {
            i.orderd = index + 1
            i.groupGridId = that.groupGridId
            if (!i.groupChildGridId) {
              i.falseFlag = false
            }
            if (i.falseFlag == true) {
              flag = true
            }
          })
          this.model.dataSource = [...this.dataSource]
          if (!flag) {
            that.confirmLoading = true
            httpAction(this.url.add, this.dataSource, 'post')
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
                this.visible = false
              })
              .finally(() => {
                this.visible = false
                that.confirmLoading = false
              })
          }
          return
        }
      })
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
    },
    StringToArr(str) {
      var list = []
      var ar2 = 0
      for (let i = 0; i < str.length - 1; i += 2) {
        list.push(str.substring(i, i + 2))
      }
      return list
    },
    handleInput(e, record) {
      record.falseFlag = false
      let val = e.target.value
      let reg = /^[A-Fa-f0-9]{2}$/
      if (!reg.test(val)) {
        record.falseFlag = true
        return false
      }
      record.Values.forEach((i, index) => {
        if (!reg.test(i)) {
          record.falseFlag = true
          return false
        }
      })
    },
    editK(record) {
      let key = record.key
      const newData = [...this.dataSource]
      const target = newData.find((item) => key == item.key)
      this.editingKey = key
      if (target) {
        target.editable1 = true
        this.dataSource = newData
      }
    },
    save(key) {
      this.cacheData = [...this.dataSource]
      const newData = [...this.dataSource]
      const newCacheData = [...this.cacheData]
      const target = newData.find((item) => key == item.key)
      const targetCache = newCacheData.find((item) => key == item.key)
      if (target && targetCache) {
        target.packageInfoId = this.packageInfoId
        delete target.editable1
        this.dataSource = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''
    },
    cancel(key) {
      const newData = [...this.dataSource]
      const target = newData.find((item) => key == item.key)
      this.editingKey = ''
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => key == item.key)
        )
        delete target.editable1
        this.dataSource = newData
      }
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find((item) => item.key == key)
      if (target) {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    },
    onDelete(record) {
      let key = record.key
      if (record.id) {
        httpAction(`${this.url.delete}?id=${record.id}`, {}, 'delete').then((res) => {
          this.$message.success(res.message)
        })
      }
      const dataSource = [...this.dataSource]
      this.dataSource = dataSource.filter((item) => item.key != key)
    },
    handleAdd() {
      const { count, dataSource } = this
      const newData = {
        key: count,
        groupChildGridId: '',
        groupGridId: this.groupGridId,
        orderd: dataSource.length + 1,
        falseFlag: false,
        length: 1,
        editable1: true,
      }
      this.dataSource = [...dataSource, newData]
      this.count = count + 1
      this.cacheData = [...this.dataSource]
    },
    formatName(text, type) {
      if (type == 'groupChildGridId') {
        let texts = this.packageGridIdList.find((i) => i.id == text)
        if (texts) {
          return texts.gridName
        } else {
          return text
        }
      }
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.visible = true
      const that = this
      this.dataSource = []
      this.model = Object.assign({}, record)
      this.model.Values = []
      this.groupGridId = record.packageGridId
      httpAction(
        `${this.url.query}?groupGridId=${record.packageGridId}`,
        {
          pageSize: -1,
          order: 'asc',
          column: 'orderd',
        },
        'post'
      ).then((res) => {
        if (res.result && res.result.length != 0) {
          res.result.forEach((i, index) => {
            i.key = index
            this.dataSource.push(i)
          })
        } else {
          this.dataSource = []
        }
        this.count = this.dataSource.length
        this.dataSource.forEach((i) => {
          // if (i.length) {
          //   if (i.isEigen == 1) {
          //     i.length = i.length
          //     this.$set(i, 'Values', [...this.StringToArr(i.eigenValue)])
          //   }
          // } else {
          //   i.length = -1
          // }
          this.dataSource = [...this.dataSource]
        })
      })
      //工程量全部列表
      getAction(`${this.url.PackageGridlist}`, { pageSize: -1 }).then((res) => {
        //该包的工程量列表
        this.packageInfoId = record.id
        this.packageGridIdList = res.result.records
      })
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          // that.confirmLoading = true
          let httpurl = ''
          let method = ''
          let flag = false
          this.dataSource.forEach((i) => {
            if (i.isEigen && i.Values) {
              if (i.Values.length > 0) {
                i.eigenValue = i.Values.join('').toUpperCase()
              }
              // delete i.Values
            }
            if (i.falseFlag == true) {
              flag = true
            }
          })
          this.model.dataSource = [...this.dataSource]
          if (!flag) {
            that.confirmLoading = true
            httpAction(this.url.addP, this.dataSource, 'post')
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
                this.visible = false
              })
              .finally(() => {
                this.visible = false
                that.confirmLoading = false
              })
          }
          return
        }
      })
    },
  },
}
</script>

<style></style>
